package com.spareparts.activity;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import cm.framework.net.ClientSession;
import cm.framework.net.ControlRunnable;
import cm.framework.net.IErrorListener;
import cm.framework.net.IResponseListener;
import cm.framework.protocol.BaseHttpRequest;
import cm.framework.protocol.BaseHttpResponse;
import cm.framework.protocol.ErrorResponse;

import com.spareparts.R;
import com.spareparts.activity.base.BaseActivityGroup;
import com.spareparts.entyties.WareHouse;
import com.spareparts.listener.OnResultListener;
import com.spareparts.listener.ResultData;
import com.spareparts.protocol.WarehouseRequest;
import com.spareparts.protocol.WarehouseResponse;
import com.spareparts.protocol.WarehouseSubmitRequest;

public class WareHouseStorageActivity extends BaseActivityGroup
{
	private Button mScanningButton;
	private Button mSubmitButton;
	private Spinner mSpinnerWarehouse;
	
	private EditText editTextBatch;
	private EditText veneercodesEditText;
	private EditText editTextHeadman;
	private EditText editTextDateline;
	private EditText editTextMark;
	
	private BaseAdapter mAdaptor;
	
	private String[] strAdaptor;
	
	private Integer type;
	
	private String isMain;
	
	private ResultData mResultData;
	
	private String mCode;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		requestWindowFeature( Window.FEATURE_NO_TITLE );
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_warehouse_storage);
		
		type = (Integer) getDataFromIntent("type");
		
		isMain = (String) getDataFromIntent("main");
		
		//判断是否从首页面传过来
		if(null != isMain && !isMain.equals(""))
		{
			mCommonApplication.mContext = this;
		}
		
		int screenWidth  = getWindowManager().getDefaultDisplay().getWidth();
		findViewById(R.id.ll01).setMinimumWidth(screenWidth);
		
		mScanningButton = (Button) findViewById(R.id.ButtonScanning);
		mSubmitButton = (Button) findViewById(R.id.ButtonSubmit);
		veneercodesEditText = (EditText) findViewById(R.id.veneercodesEditText);
		editTextBatch = (EditText) findViewById(R.id.editTextBatch);
		editTextHeadman = (EditText) findViewById(R.id.editTextHeadman);
		editTextDateline = (EditText) findViewById(R.id.editTextDateline);
		editTextMark = (EditText) findViewById(R.id.editTextMark);
		mSpinnerWarehouse = (Spinner) findViewById(R.id.spinnerWarehouse);
		
		mScanningButton.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) 
			{
				Intent intent = new Intent();
				intent.setClass(WareHouseStorageActivity.this, CameraActivity.class);
				startActivityForResult(intent, 0);
			}
		});
		
		if(null != mCommonApplication.mUserInfo)
		{
			editTextHeadman.setText(mCommonApplication.mUserInfo.userName);
		}
		
		editTextDateline.setText(getNowTime());
		setInit();
		
		if(null == mCommonApplication.mWareHouseList || mCommonApplication.mWareHouseList.size()<1)
		{
			getWareHouse();
		}
		
		mResultData = new ResultData();
		mResultData.setOnResultListener(new OnResultListener() 
		{
			@Override
			public void onResult(String code) 
			{	
				/*
				 * 飞哥让注释掉
				 * 2014/5/8 9:35 
				 */
				String newCode = setCode(code);
				String oldCode = veneercodesEditText.getText().toString();
				if(null != oldCode && !"".equals(oldCode.trim()))
				{
					oldCode = oldCode + "\n" + newCode;
					mCode = mCode + "\n" + code;
				}
				else
				{
					oldCode = newCode;
					mCode = code;
				}
				//输入文本输入框中
				veneercodesEditText.setText(oldCode);
			}
		});
		mCommonApplication.mResultData = mResultData;
	}
	
	/**
	 * 设置扫描到的编码：
	 * 	扫码结果是以21开头的数字串，需要将21去掉，然后取8位数存入数据库
 	 *	扫码结果是其他数字开头的，需要在数字串前面加上03，然后取前6位。共计8位数字存入数据库
	 * @param code
	 * @return
	 */
	public String setCode(String code)
	{
		String head = code.substring(0, 2);
		
		String rs = "";
		if(head.equals("21"))
		{
			if(code.length()>=10)
			{
				rs = code.substring(2, 10);
			}
		}
		else
		{
			if(code.length()>=6)
			{
				rs = "03" + code.substring(0, 6);
			}
		}
		return rs;
	}
	
	/**
	 * 设置单击事件
	 */
	private void setInit()
	{
		editTextDateline.setOnTouchListener(new OnTouchListener() 
		{
			@Override
			public boolean onTouch(View v, MotionEvent event) 
			{
				if (event.getAction() == MotionEvent.ACTION_DOWN) 
				{ 
					AlertDialog.Builder builder = new AlertDialog.Builder(mCommonApplication.mContext);  
		            View view = View.inflate(mCommonApplication.mContext, R.layout.view_date_selected, null);  
		            final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);  
		            builder.setView(view);  
		  
		            Calendar cal = Calendar.getInstance();  
		            cal.setTimeInMillis(System.currentTimeMillis());  
		            datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null);  
	                
		            builder.setTitle("选取起始时间");  
	                builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() 
	                {  
		                    @Override  
		                    public void onClick(DialogInterface dialog, int which) 
		                    {  
		                        StringBuffer sb = new StringBuffer();  
		                        sb.append(String.format("%d-%02d-%02d",   
		                                datePicker.getYear(),   
		                                datePicker.getMonth() + 1,  
		                                datePicker.getDayOfMonth()));  
		                        editTextDateline.setText(sb);  
		                        dialog.cancel();  
		                    }  
		                });  
		            Dialog dialog = builder.create();  
		            dialog.show();
				}
				return false;
			}
		});
		
		mSubmitButton.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) 
			{
				setSubmit();
			}
		});

		setSpinner();
	}
	
	/**
	 * 设置Spinner
	 */
	private void setSpinner()
	{
		if(null != mCommonApplication.mWareHouseList && mCommonApplication.mWareHouseList.size()>0)
		{
			strAdaptor = new String[mCommonApplication.mWareHouseList.size()];
			for(int i=0;i<mCommonApplication.mWareHouseList.size();i++)
			{
				WareHouse oWareHouse = mCommonApplication.mWareHouseList.get(i);
				strAdaptor[i] = oWareHouse.wName;
			}
			mAdaptor = new BaseAdapter()
			{

				@Override
				public int getCount() {
					return strAdaptor.length;
				}

				@Override
				public Object getItem(int position) {
					return strAdaptor[position];
				}

				@Override
				public long getItemId(int position) {
					return position;
				}

				@Override
				public View getView(int position, View convertView,
						ViewGroup parent) 
				{
					TextView tv = new TextView(mContext);
					tv.setText(getItem(position).toString());
					tv.setTextSize(16);
					return tv;
				}
				
			};
			mSpinnerWarehouse.setAdapter(mAdaptor);
		}
	}
	
	/**
	 * 
	 */
	private void setSubmit()
	{
		if(veneercodesEditText.getText().toString().trim().equals(""))
		{
			mHandler.sendEmptyMessage(2);
			return ;
		}
		if(editTextHeadman.getText().toString().trim().equals(""))
		{
			mHandler.sendEmptyMessage(3);
			return ;
		}
		String uid = "";
		if(null != mCommonApplication.mUserInfo)
		{
			uid = mCommonApplication.mUserInfo.userId;
		}
		String wid="";
		if(null != mCommonApplication.mWareHouseList && mCommonApplication.mWareHouseList.size()>0)
		{
			for(WareHouse oWareHouse : mCommonApplication.mWareHouseList)
			{
				if(mSpinnerWarehouse.getSelectedItem().toString().equals(oWareHouse.wName))
				{
					wid = oWareHouse.wid;
				}
			}
		}
		
//		String veneercodes = veneercodesEditText.getText().toString();
		String veneercodes = mCode;
		if(null != veneercodes)
		{
			veneercodes = veneercodes.replaceAll("\n", ",");
		}
		
		ClientSession.getInstance().setDefErrorReceiver(mStateAlert);
		ClientSession.getInstance().setDefStateReceiver(mStateAlert);
		ClientSession.getInstance().asynGetResponse(new WarehouseSubmitRequest(uid,
				editTextBatch.getText().toString().trim(),veneercodes,
				editTextHeadman.getText().toString().trim(),editTextDateline.getText().toString().trim(),
				editTextMark.getText().toString().trim(),wid,type),
				new IResponseListener()
				{
					@Override
					public void onResponse(BaseHttpResponse arg0, BaseHttpRequest arg1,ControlRunnable arg2) 
					{
						mHandler.sendEmptyMessage(5);
					}
		},new IErrorListener() 
		{
			@Override
			public void onError(ErrorResponse arg0, BaseHttpRequest arg1,
					ControlRunnable arg2) 
			{
				
			}
		});
	}
	
	/**
	 * 获取可操作的仓库
	 */
	public void getWareHouse()
	{
		String uid = "";
		if(null != mCommonApplication.mUserInfo)
		{
			uid = mCommonApplication.mUserInfo.userId;
		}
		
		ClientSession.getInstance().setDefErrorReceiver(mStateAlert);
		ClientSession.getInstance().setDefStateReceiver(mStateAlert);
		ClientSession.getInstance().asynGetResponse(new WarehouseRequest(uid),
				new IResponseListener()
				{
					@Override
					public void onResponse(BaseHttpResponse arg0, BaseHttpRequest arg1,ControlRunnable arg2) 
					{
						WarehouseResponse warehouseResponse = (WarehouseResponse) arg0;
						mCommonApplication.mWareHouseList = warehouseResponse.mWareHouseList;
						mHandler.sendEmptyMessage(1);
					}
		},new IErrorListener() 
		{
			@Override
			public void onError(ErrorResponse arg0, BaseHttpRequest arg1,
					ControlRunnable arg2) 
			{
				if(null != arg0 && null != arg0.getErrorDesc() && !arg0.getErrorDesc().trim().equals(""))
				{
					Message msg = new Message();
					msg.what = 4;
					msg.obj = arg0.getErrorDesc();
					mHandler.sendMessage(msg);
				}
			}
		});
	}
	
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler()
	{
		@Override
		public void dispatchMessage(Message msg) 
		{
			super.dispatchMessage(msg);
			
			switch(msg.what)
			{
				case 1:
					setSpinner();
					break;
				case 2:
					showToast("单板条码不能为空");
					break;
				case 3:
					showToast("经办人不能为空");
					break;
				case 4:
					String str = msg.obj.toString();
					showToast(str);
					break;
				case 5:
					showToast("提交成功!");
					break;
			}
		}
	};
	
	/**
	 * 获取系统当前时间
	 * @return
	 */
	@SuppressLint("SimpleDateFormat")
	private String getNowTime()
	{
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		//返回的条形码数据
//		String code = data.getStringExtra("Code");
//
//		String oldCode = veneercodesEditText.getText().toString();
//		if(null != oldCode && !"".equals(oldCode.trim()))
//		{
//			oldCode = oldCode + "\n" + code;
//		}
//		else
//		{
//			oldCode = code;
//		}
//		//输入文本输入框中
//		veneercodesEditText.setText(oldCode);
		
		super.onActivityResult(requestCode, resultCode, data);
	}
	
}
